import { defineStore } from 'pinia'
import oilPriceService, { type OilPriceData } from '@/services/oilPriceService'

export interface OilPriceState {
  prices: OilPriceData[]
  loading: boolean
  selectedProvince: string
  provinces: string[]
  oilTypes: string[]
  lastUpdated: string | null
}

export const useOilPriceStore = defineStore('oilPrice', {
  state: (): OilPriceState => ({
    prices: [],
    loading: false,
    selectedProvince: '',
    provinces: [],
    oilTypes: [],
    lastUpdated: null
  }),

  getters: {
    /**
     * 按省份分组的油价数据
     */
    pricesByProvince: (state): Record<string, OilPriceData[]> => {
      const grouped: Record<string, OilPriceData[]> = {}
      state.prices.forEach(price => {
        if (!grouped[price.province]) {
          grouped[price.province] = []
        }
        grouped[price.province].push(price)
      })
      return grouped
    },

    /**
     * 按油品类型分组的油价数据
     */
    pricesByOilType: (state): Record<string, OilPriceData[]> => {
      const grouped: Record<string, OilPriceData[]> = {}
      state.prices.forEach(price => {
        if (!grouped[price.oilType]) {
          grouped[price.oilType] = []
        }
        grouped[price.oilType].push(price)
      })
      return grouped
    },

    /**
     * 当前选中的省份数据
     */
    currentProvincePrices: (state): OilPriceData[] => {
      if (!state.selectedProvince) {
        return state.prices
      }
      return state.prices.filter(price => price.province === state.selectedProvince)
    }
  },

  actions: {
    /**
     * 初始化数据 - 仅加载省份和油品类型，不自动查询油价
     */
    async initialize() {
      this.provinces = oilPriceService.getSupportedProvinces()
      this.oilTypes = oilPriceService.getSupportedOilTypes()
      // 不自动加载油价数据，改为按需查询
    },

    /**
     * 获取油价数据
     */
    async fetchOilPrices() {
      this.loading = true
      try {
        const response = await oilPriceService.getTodayOilPrices(this.selectedProvince)
        if (response.success) {
          this.prices = response.data
          this.lastUpdated = response.timestamp
        } else {
          throw new Error(response.message)
        }
      } catch (error) {
        console.error('获取油价数据失败:', error)
        // 可以在这里添加错误提示
      } finally {
        this.loading = false
      }
    },

    /**
     * 设置选中的省份
     */
    setSelectedProvince(province: string) {
      this.selectedProvince = province
      this.fetchOilPrices()
    },

    /**
     * 刷新数据
     */
    async refreshData() {
      await this.fetchOilPrices()
    }
  }
})